package com.easylinkin.linkappapi.common.utils;

import com.alibaba.excel.write.handler.AbstractRowWriteHandler;
import com.alibaba.excel.write.handler.RowWriteHandler;
import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;

public class MergeStrategy implements RowWriteHandler {
    private Integer startMergeRow = null;
    private int mergeCount = 0;

    @Override
    public void afterRowDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Integer relativeRowIndex, Boolean isHead) {
        if (isHead) {
            return;
        }

        Cell serialCell = row.getCell(0);
        if (serialCell != null && serialCell.getCellType() != org.apache.poi.ss.usermodel.CellType.BLANK) {
            if (startMergeRow != null) {
                mergeRows(writeSheetHolder, startMergeRow, row.getRowNum() - 1);
            }
            startMergeRow = row.getRowNum();
            mergeCount = 1;
        } else if (startMergeRow != null) {
            mergeCount++;
        }
    }


    private void mergeRows(WriteSheetHolder writeSheetHolder, int startRow, int endRow) {
        if (startRow >= endRow) {
            return;
        }
        Sheet sheet = writeSheetHolder.getSheet();
        // 合并序号列(第0列)
        sheet.addMergedRegion(new CellRangeAddress(startRow, endRow, 0, 0));
        // 合并检查项目列(第1列)
        sheet.addMergedRegion(new CellRangeAddress(startRow, endRow, 1, 1));
    }
}